package com.qianfeng.vhly.youshare.tasks;

import android.os.AsyncTask;
import com.qianfeng.vhly.youshare.Constants;
import com.qianfeng.vhly.youshare.utils.HttpTool;
import org.json.JSONObject;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/2/5
 * Email: vhly@163.com
 */

/**
 * 获取产品列表接口调用，这个异步任务在 核心产品与平台产品中都使用到了
 */
public class ProductListTask extends AsyncTask<String, Integer, JSONObject> {

    private TaskProcessor processor;

    public ProductListTask(TaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        JSONObject ret = null;
        if (params != null && params.length > 0) {
            // 产品列表接口，支持指定分类ID, 用于获取指定分类下的产品列表
            String id = params[0];

            String size = "5";

            String page = "1";

//            switch (params.length){
//                case 3:
//                    page = params[2];
//                case 2:
//                    size = params[1];
//                    break;
//            }

            switch (params.length) {
                case 2: // 只有两个
                    size = params[1];
                    break;
                case 3:
                    size = params[1];
                    page = params[2];
                    break;
            }
            // GET 请求 参数 采用 key=value&key=value
            String url = Constants.API_POINT + "/category.php?id="
                    + id
                    + "&size=" + size
                    + "&page=" + page; // 获取产品分类商品列表的接口

            byte[] bytes = HttpTool.get(url);

            if (bytes != null) {
                try {
                    String str = new String(bytes, "UTF-8");
                    ret = new JSONObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }
        return ret;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        if(processor != null){
            processor.processResult(jsonObject);
        }
    }
}
